package com.example.sale.Controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sale.Result.R;
import com.example.sale.SelfUtil.MakeCaptcha;
import com.example.sale.Service.IUserDetailService;
import com.example.sale.Service.IUserService;
import com.example.sale.Service.imply.UserDetailService;
import com.example.sale.True.Birthday;
import com.example.sale.True.User;
import com.example.sale.True.UserDetail;
import com.example.sale.True.Verification;
import com.example.sale.utils.JwtUtil;
import com.example.sale.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("userDetail")
public class UserDetailController {
    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IUserDetailService iUserDetailService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UploadFileController uploadFileController;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserDetailService userDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //添加单个人的数据在管理员的列表中
    @PostMapping("/data")
    public Map<String, Object> getData(
            HttpServletRequest request,
            @RequestParam("userDetail") String userDetail,
            @RequestParam("img") MultipartFile file) throws IOException {
        System.out.println("user is " + userDetail);
//        System.out.println("file is " + file);
        UserDetail detail = JSONObject.parseObject(userDetail, UserDetail.class);

        String token = request.getHeader("token");
        User zhi = jwtUtil.parseToken(token, User.class);
        Integer id = zhi.getId(); // 假设id是String类型
        Map<String, Object> response = new HashMap<>();
        detail.setUserid(id);
        String img = uploadFileController.upImg(file);
        detail.setImg(img);
        userDetailService.clearCache();
        response.put("stata", "success");
        response.put("boolean", iUserDetailService.save(detail));
        return response;
    }
    //获取所有人的数据
    @GetMapping("/getAll")
//    @Cacheable(value = "searchUsers", key = "root.method.name")
    public Map<String, Object> getData(){
        Map<String,Object> result = new HashMap<>();
        result.put("data",iUserDetailService.list());
        System.out.println("后端数据 "+iUserDetailService.list());
        return result;
    }
    //删除单个人的数据
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteData(@PathVariable Integer id){
        System.out.println("id is "+id);
        Map<String,Object> result = new HashMap<>();
        UserDetail userDetail =iUserDetailService.getById(id);
        System.out.println(userDetail);
        Integer userid = userDetail.getUserid();
        System.out.println("userid is "+ userid);
        result.put("id",iUserDetailService.removeById(id));
        //获取对应的那个人的userid并且把那个登录的也删了
        userDetailService.clearCache();
        iUserService.deleteFeedBackByUserId(userid);
        iUserService.deleteProductListDetailByUserId(userid);
        iUserService.removeBYTokenId(userid);
        return result;
    }
    //获取单个人的数据
    @GetMapping("/{id}")
    public Map<String,Object> getById(@PathVariable Integer id){
        Map<String,Object> result = new HashMap<>();
        result.put("data",iUserDetailService.getById(id));
        return result;
    }
    //编辑单个人的数据
    @PutMapping("/detailData")
    public Map<String, Object> changeData(
            HttpServletRequest request,
            @RequestParam("userDetail") String userDetail,
            @RequestParam(value = "img", required = false) MultipartFile file) throws IOException {
        System.out.println("user is " + userDetail);
        UserDetail detail = JSONObject.parseObject(userDetail, UserDetail.class);
//        String token = request.getHeader("token");
//        User zhi = jwtUtil.parseToken(token, User.class);
//        Integer id = zhi.getId(); // 假设id是String类型
        Map<String, Object> response = new HashMap<>();
//        detail.setUserid(id);
        // 判断图片字段类型
        if (file != null && !file.isEmpty()) {
            // 处理新上传的图片
            String img = uploadFileController.upImg(file);
            detail.setImg(img);
        } else if (detail.getImg() == null || !detail.getImg().startsWith("http")) {
            // 如果图片字段不是 multipart 文件且不是原始 OSS 链接，则将图片字段设置为 null
            detail.setImg(null);
        }
        response.put("stata", "success");
        response.put("boolean", iUserDetailService.updateById(detail));
        userDetailService.clearCache();
        return response;
        }
        @GetMapping("/search")
        @Cacheable(value = "pageData", key = "#pageNO + ':' + #name + ':' + #address + ':' + #age")
        public Map<String,Object>SearchData(
                @RequestParam(value ="name",required = false)String name,
                @RequestParam(value ="address",required = false)String address,
                @RequestParam(value = "age",required = false)Integer age,
                @RequestParam(value = "pageNo") Integer pageNO,
                @RequestParam(value = "pageSize") Integer pageSize)
        {
            String ageString = null;
            if (age != null) {
                ageString = age.toString();
            }
            System.out.println("name is"+name);
            System.out.println("address is"+address);
            System.out.println("age is"+age);
            System.out.println("pageNo is"+pageNO);
            System.out.println("pageSize is "+pageSize);
            LambdaQueryWrapper<UserDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StringUtils.hasLength(name),UserDetail::getName,name);
            wrapper.eq(StringUtils.hasLength(ageString),UserDetail::getAge,age);
            wrapper.eq(StringUtils.hasLength(address),UserDetail::getAddress,address);
            Page<UserDetail> page =new Page<>(pageNO,pageSize);
            Map<String,Object> result = new HashMap<>();
            iUserDetailService.page(page,wrapper);
//            List<UserDetail> userDetailList = iUserDetailService.searchUsers(name, address, age);
//            System.out.println(userDetailList);
            result.put("status",page.getTotal());
            result.put("data",page.getRecords());
//            result.put("data",userDetailList);
//            result.put("size",userDetailList.size());
            return result;
        }
        @PostMapping  ("DeleteByIds")
        public Map<String,Object>deleteByIds(@RequestBody List<Integer>Ids){
            System.out.println(Ids);
             iUserDetailService.removeByIds(Ids);
             Map<String,Object> result = new HashMap<>();
             result.put("data","success");
             userDetailService.clearCache();
             return result;
        }
        //用户的视角中新增个人的信息到这里
        @PostMapping("/selfData")
        public Map<String, Object> getData(@RequestBody UserDetail userDetail,HttpServletRequest request)  {
            System.out.println("进入新增的个人信息的接口了");
            System.out.println("user is " + userDetail);
//        System.out.println("file is " + file);
            String token = request.getHeader("token");
            User zhi = jwtUtil.parseToken(token, User.class);
            Integer id = zhi.getId(); // 假设id是String类型
            Map<String, Object> response = new HashMap<>();
            userDetailService.clearCache();
            userDetail.setUserid(id);
            boolean status =iUserDetailService.save(userDetail);
            response.put("stata", "success");
            response.put("boolean", status);
            return response;
        }
        //清除缓存数据的方法
        //防止用户重复提交申请检查一下是否提交过个人的信息
        @PostMapping("checkExist")
        public Map<String,Object>Post(HttpServletRequest request){
            System.out.println("进入这个checkExist接口了");
            String token = request.getHeader("token");
            User zhi = jwtUtil.parseToken(token, User.class);
            Integer id = zhi.getId(); // 假设id是String类型
            System.out.println(id);
            boolean userDetailExists = iUserDetailService.isUsernameExists(id);
            Map<String, Object> response = new HashMap<>();
            if (userDetailExists){
                response.put("status","true");
            }
            else {
                response.put("status","false");
            }
            return response;
        }
        //获取用户自己提交的那个数据然后展示
        @GetMapping("detailId")
        public Map<String,Object> getById(HttpServletRequest request){
            String token = request.getHeader("token");
            User zhi = jwtUtil.parseToken(token, User.class);
            Integer id = zhi.getId(); // 假设id是String类型
            Map<String,Object> result = new HashMap<>();
            System.out.println("进入这个detailId接口了");
            result.put("data",iUserDetailService.getByTokenId(id));
            result.put("status",iUserDetailService.isUserDetailExists(id));
            System.out.println(result);
            System.out.println("你看看result是什么");
            return result;
        }
        //更据TokenId来获取用户自己的头像然后展示出来
        @GetMapping("photo")
        public Map<String,Object> getPhotoById(HttpServletRequest request){
            String token = request.getHeader("token");
            User zhi = jwtUtil.parseToken(token, User.class);
            Integer id = zhi.getId(); // 假设id是String类型
            Map<String,Object> result = new HashMap<>();
            result.put("data",iUserDetailService.getByPhotoId(id));
            System.out.println(result);
            return result;
        }
        @GetMapping("username")
        public Map<String,Object> getNameById(HttpServletRequest request){
            String token = request.getHeader("token");
            User zhi = jwtUtil.parseToken(token, User.class);
            Integer id = zhi.getId(); // 假设id是String类型
            Map<String,Object> result = new HashMap<>();
            result.put("data",iUserDetailService.getByNameId(id));
            System.out.println(result);
            return result;
        }
        @DeleteMapping("/self")
        public Map<String, Object> deleteData(HttpServletRequest request){
            String token = request.getHeader("token");
            User zhi = jwtUtil.parseToken(token, User.class);
            Integer userid = zhi.getId(); // 假设id是String类型
            Map<String,Object> result = new HashMap<>();
            userDetailService.clearCache();
            iUserService.deleteProductListDetailByUserId(userid);
            result.put("status","success");
            return result;
        }
        @GetMapping("people")
        public List<Map<String,Object>> getPeopleNumber(){
            String Girl = "女";
            String Boy = "男";
            List<Map<String, Object>> dataList = new ArrayList<>();
            Map<String,Object> People = new HashMap<>();
            People.put("value",Integer.valueOf(iUserDetailService.GetAgeNumberMore(18)));
            People.put("name","成年人数");
            dataList.add(People);
            Map<String,Object> YoungPeople= new HashMap<>();
            YoungPeople.put("value",Integer.valueOf(iUserDetailService.GetAgeNumberLess(18)));
            YoungPeople.put("name","未成年人数");
            dataList.add(YoungPeople);
            Map<String,Object> GirlPeople= new HashMap<>();
            GirlPeople.put("value",Integer.valueOf(iUserDetailService.findGenderNumber(Girl)));
            GirlPeople.put("name","女性人数");
            System.out.println();
            dataList.add(GirlPeople);
            Map<String,Object> BoyPeople= new HashMap<>();
            BoyPeople.put("value",Integer.valueOf(iUserDetailService.findGenderNumber(Boy)));
            BoyPeople.put("name","男性人数");
            dataList.add(BoyPeople);
            return dataList;
        }
    @GetMapping("BirthdayData")
    public List<List<Birthday>> GetBirthDayNumber(){
        String[] months = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
        List<List<Birthday>> dataList = new ArrayList<>();
        for(String month : months){
            if (iUserDetailService.findBirthdayNumber(month).isEmpty()){
                Birthday birthday = new Birthday();
                birthday.setMonth(Integer.valueOf(month));
                birthday.setCount(0);
                List<Birthday> birthdayList = new ArrayList<>();
                birthdayList.add(birthday);
                dataList.add(birthdayList);
            }
            else{
                dataList.add(iUserDetailService.findBirthdayNumber(month));
            }
        }
        return  dataList;
    }
    @PostMapping("checkValid")
    public Map<String, Object> getCheck(@RequestParam(value = "username") String username,
                                        @RequestParam(value = "qq") String qq,
                                        @RequestParam(value = "key") String key)

    {
        System.out.println(username);
        System.out.println(qq);
        System.out.println(key);
        String QQ = qq + "@qq.com";
        String text = "忘记密码的验证码";
        Map map = new HashMap();
        if (qq.equals(iUserDetailService.getQQNumber(username))){
            String verificationCode = MakeCaptcha.generateCaptcha();
            //设置qq验证码的
            Verification verification = new Verification();
            verification.setKey(key);
            verification.setVscode(verificationCode);
//            rabbitTemplate.convertAndSend("hmall.direct","red",verification);
            //测试是否把验证码给存进去了
            stringRedisTemplate.opsForValue().set(key, verificationCode, 60, TimeUnit.SECONDS);
            mailUtils.sendMail(QQ,verificationCode,text);
            map.put("status","success");
            return map;
        }
        else{
            map.put("status","false");
            return  map;
        }
    }
    @PostMapping ("GetCheckNumber")
    public Map <String,Object> GetCheckNumber(@RequestParam(value = "key") String key,
                                              @RequestParam(value = "vscode") String vscode,
                                              @RequestParam(value = "username") String username,
                                              @RequestParam(value = "qq") String qq)
    {
         Map map = new HashMap<>();
         final  String message = "您的登录密码";
         String QQ = qq+"@qq.com";
         String code = stringRedisTemplate.opsForValue().get(key);
         if(code.equals(vscode)){
             String password = iUserDetailService.getPassword(username);
             mailUtils.sendMail(QQ,password,message);
             map.put("status","success");
             return map;
         }
         map.put("status","false");
         return  map;
    }
}
